//
//  AddMoneyHistoryViewController.m
//  PeopleStreet
//
//  Created by 刘建峰 on 16/6/7.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "AddMoneyHistoryViewController.h"
#import "AddMoneyHistoryTableViewCell.h"
static NSString * cellIdentify = @"AddMoneyHistoryTableViewCell";
@interface AddMoneyHistoryViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *array;
@end

@implementation AddMoneyHistoryViewController


- (void)viewWillAppear:(BOOL)animated{
    [self.tableView.header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _array = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    [self.tableView registerNib:[UINib nibWithNibName:cellIdentify bundle:nil] forCellReuseIdentifier:cellIdentify];
    _tableView.dataSource = self;
    _tableView.delegate = self;
}

- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self getBillingRecords];
        });
    }];
    [_tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.array.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self getBillingRecords];
        });
    }
}

#pragma mark == 账单记录
- (void)getBillingRecords{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    self.shareApi.delegate=self;
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msceMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryMemberEpurseFlow withHttpType:@"POST" withTag:SX_SX_queryMemberEpurseFlow];
}

#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _array.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80*VerticalRatio();
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AddMoneyHistoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (cell == nil) {
        cell= [[AddMoneyHistoryTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
        
    }
    
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    cell.titleLabel.text = [NSString stringWithFormat:@"%@",_array[indexPath.row][@"meflRemark"]];
    NSString *meflDirection = [NSString stringWithFormat:@"%@",_array[indexPath.row][@"meflDirection"]];
    if ([meflDirection isEqualToString:@"1"]) {
        cell.detailLabel.text = @"充值成功";
    } else if ([meflDirection isEqualToString:@"2"]) {
        cell.detailLabel.text = @"交易成功";
    }
    
    NSString *time = [NSString stringWithFormat:@"%@",_array[indexPath.row][@"meflCreateTime"]];
    long long Time=[time longLongValue];
    NSDate *Date = [[NSDate alloc]initWithTimeIntervalSince1970:Time/1000.0];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy:MM:dd"];
    time = [formatter stringFromDate:Date];
    
    NSDate *date = [NSDate date];
    NSDateFormatter *formatterNow = [[NSDateFormatter alloc] init];
    [formatterNow setDateStyle:NSDateFormatterMediumStyle];
    [formatterNow setTimeStyle:NSDateFormatterShortStyle];
    [formatterNow setDateFormat:@"YYYY-MM-dd"];
    NSString *DateNow = [formatterNow stringFromDate:date];
    
    if ([time isEqualToString:DateNow]) {
        [formatter setDateFormat:@"hh:mm"];
        time = [formatter stringFromDate:Date];
        cell.timeLabel.text = [NSString stringWithFormat:@"今天 %@",time];
    } else {
        [formatter setDateFormat:@"YYYY-MM-dd hh:mm"];
        time = [formatter stringFromDate:Date];
        cell.timeLabel.text = time;
    }
    
    cell.timeLabel.text = time;
    
    [cell.gold setTitle:[NSString stringWithFormat:@" + %@",_array[indexPath.row][@"meflAmount"]] forState:UIControlStateNormal];
    [cell.silver setTitle:[NSString stringWithFormat:@" + %@",_array[indexPath.row][@"meflSilver"]] forState:UIControlStateNormal];
    return cell;
    
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.footer endRefreshing];
    [_tableView.header endRefreshing];
    if (tag == SX_SX_queryMemberEpurseFlow){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.array removeAllObjects];
                }
                
                NSMutableDictionary *dic = database[@"result"];
                if ([dic.allKeys containsObject:@"pageRecord"]) {
                    NSArray *arr = database[@"result"][@"pageRecord"];
                    for (id entity in arr) {
                        [self.array addObject:entity];
                    }
                }
                
                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData]; 
            });
        }
    }
    
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    [_tableView.footer endRefreshing];
    [_tableView.header endRefreshing];
    [self dismissWaitDialog];
    
    
}



@end
